package com.tale.springbootatm.common.aop;

import com.tale.springbootatm.common.util.IpUtil;
import com.tale.springbootatm.common.util.R;
import com.tale.springbootatm.dao.LoginInfoRep;
import com.tale.springbootatm.entity.LoginInfo;
import com.tale.springbootatm.entity.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * aop面向切面记录日志
 *
 * author: 蔡奇峰
 * date: 2020/4/17 16:08
 **/
@Component
@Aspect
public class LoginLogAspect {

    @Autowired
    private LoginInfoRep loginInfoRep;

    /**
     * 登录方法切入点
     */
    @Pointcut("execution(public * com.tale.springbootatm.controller.UserController.login(..))")// 切入点位置
    public void loginLog() {}


    /**
     * 记录登录认证
     *
     * @param joinPoint
     * @param result 当前切入点返回的对象
     */
    @AfterReturning(value = "loginLog()", returning = "result")
    public void saveLog(JoinPoint joinPoint, Object result){

        System.out.println("result-->" + result);
        LoginInfo loginInfo = new LoginInfo();

        Object[] args = joinPoint.getArgs();
        User user = null;
        if (args[0] instanceof User){
            user = (User) args[0];

            loginInfo.setUserName(user.getBankCard() + "");
        }
        String status = "";
        String msg = "";
        if (result instanceof R){

            R r = (R) result;

            msg = r.getMessage();

            status = r.isSuccess() ? "0" : "1";

        }
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

        loginInfo.setMsg(msg);
        loginInfo.setStatus(status);

        loginInfo.setLoginTime(new Date());

        String ip = IpUtil.getIpAddress(request);
        loginInfo.setIpAddr(ip);

        loginInfo.setLoginLocation(IpUtil.getCityInfo(ip));

        System.out.println("info-->" + loginInfo.toString());

        loginInfoRep.save(loginInfo);

    }

}
